package conn

import (
	"github.com/azshara/dreamwork/com"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"log"
	"time"
)

func MysConn() *sqlx.DB {
	db, err := sqlx.Open(com.DbType, com.DbConnAddr)
	if err != nil {
		panic("connect to mysql failed, " + err.Error())
	}
	db.SetMaxIdleConns(10)
	db.SetMaxOpenConns(30)
	db.SetConnMaxLifetime(time.Second * 60)
	return db
}

func TxExec(exec func(tx *sqlx.Tx, e interface{}) (interface{}, error)) (error, interface{}) {
	db := MysConn()
	defer func() {
		if err := db.Close(); err != nil {
			log.Printf("err is: %v", err)
		}
	}()
	tx := db.MustBegin()

	rs, err := exec(tx)
	if err != nil {
		if err = tx.Rollback(); err != nil {
			log.Printf("rollback err is: %v\n", err)
			return err, nil
			//panic(common.NewErrInfo(common.ErrMySQLCode, common.ErrMySQLMsg, err))
		}
	}

	if err = tx.Commit(); err != nil {
		log.Printf("commit err is: %v\n", err)
		return err, nil
		//panic(common.NewErrInfo(common.ErrMySQLCode, common.ErrMySQLMsg, err))
	}

	return nil, rs
}

func MustQuery(query func(db *sqlx.DB) (interface{}, error)) interface{} {
	db := MysConn()
	defer func() {
		if err := db.Close(); err != nil {
			log.Printf("err is: %v", err)
			//panic(common.NewErrInfo(common.ErrMySQLCode, common.ErrMySQLMsg, err))
		}
	}()

	rs, err := query(db)
	if err != nil {
		log.Printf("mysql query err is: %v\n", err)
		//panic(common.NewErrInfo(common.ErrMySQLCode, common.ErrMySQLMsg, err))
	}

	return rs
}
